package net.magicalcloud.magicalcloud.transfer;

import android.content.Context;

import net.magicalcloud.magicalcloud.transfer.bean.DownloadInfo;
import net.magicalcloud.magicalcloud.transfer.bean.ThreadInfo;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * Created by Pei on 2018/6/12.
 */

public class InitThread extends Thread {

    private DownloadInfo mDownloadInfo;
    private Context mContext;
    private ExecutorService mThreadPool;

    //默认六线程
    public static final int DEFAULT_THREAD_NUM=6;

    //各个线程的下载进度
    private int[] mTotalFinished;

    /**
     * 构造函数
     * @param context context
     * @param downloadInfo 下载信息
     * @param executorService 线程池
     */
    public InitThread(Context context,DownloadInfo downloadInfo,ExecutorService executorService){
        mContext=context;
        mDownloadInfo=downloadInfo;
        mThreadPool=executorService;

        mTotalFinished = new int[DEFAULT_THREAD_NUM];
    }

    @Override
    public void run() {
        super.run();

        try {

            URL url=new URL(mDownloadInfo.url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            int status = conn.getResponseCode();
            if(status == 200){
                int length = conn.getContentLength();       //单位为字节  ，1 kb=1024字节
                mDownloadInfo.lenght=length;
                if(length<0){
                    return;
                }

                File file = new File("/sdcard/MagicalCloud/");
                if (!file.exists()) {
                    if(!file.mkdir())
                        System.out.println("文件夹创建失败");
                }

                RandomAccessFile raf = new RandomAccessFile(new File(mDownloadInfo.filePath,mDownloadInfo.fileName),"rwd");
                raf.setLength(length);
                raf.close();
                conn.disconnect();



                List<ThreadInfo> threadInfoList = new LinkedList<>(); //建立线程信息列表

                int block = mDownloadInfo.lenght/DEFAULT_THREAD_NUM; //将下载文件分段
                if(block > 0) {
                    //start 根据线程数量分别建立线程信息
                    for(int i = 0;i < DEFAULT_THREAD_NUM;i++) {
                        ThreadInfo info = new ThreadInfo(i,mDownloadInfo.url,i*block,(i+1)*block-1,0);
                        if(i == DEFAULT_THREAD_NUM -1) {
                            info.end = mDownloadInfo.lenght; //分段最后一个，结束位置到文件总长度末尾
                        }
                        threadInfoList.add(info);         //加入列表
                    }
                }

                //start 启动各个下载线程
                for(ThreadInfo info : threadInfoList) {
                    DownloadThread thread = new DownloadThread(mDownloadInfo,info,mTotalFinished);
                    System.out.println("线程"+info.id+"下载:---"+info.start+"--->"+info.end);
                    if(!mThreadPool.isShutdown()) {
                        mThreadPool.execute(thread);
                    }

                }



//                //开启5个线程来下载当前资源..
//                int blockSize = length/threadCount ;
//
//                for(int threadID=1;threadID<=threadCount;threadID++){
//
//                    int startIndex = (threadID-1)*blockSize;
//                    int endIndex = threadID*blockSize -1;
//
//                    if(threadID == threadCount){
//                        endIndex = length;
//                    }
//                    System.out.println("线程"+threadID+"下载:---"+startIndex+"--->"+endIndex);
//                    Runnable r=new DownLoadThread(threadID, startIndex, endIndex, path) ;
//                    fixedThreadPool.execute(r);
//                }
            }

        }catch (Exception ignored){

        }

    }
}
